using UnityEngine;
using System.Collections;
using UtilConstants;

/**
 * Inheritors should override ClickAction()
 * This is the action that will happen when interacting with (i.e. clicking on) the NPC
 * The rest is some messiness in registering with the RaycastIO global to handle the clicks
 */
public class DialogueNPC : MonoBehaviour, IRaycastClickable {
	/* Max distance from character that's allowed for dialogue to happen */
	const float MAX_TALK_DISTANCE = 6.0f;
	const int REGISTER_UPDATE_INTERVAL = 10;
	int intervals = 0;
	bool registered = false;
	GlobalAccess globals;
	
	void Awake() {
		this.globals = new GlobalAccess();
	}
	
	void RegisterWithGlobal() {
		if (this.intervals < DialogueNPC.REGISTER_UPDATE_INTERVAL) {
			this.intervals = this.intervals + 1;
			return;
		}

		this.intervals = 0;
		
		/**
		 * TODO: get mouse button indirectly by looking up NPCClick or something 
		 * That way it's easy to change the mouse button
		 */
		this.registered = RaycastIO.RegisterRaycastClickable(
			this.globals, this, UtilConstants.MouseButton.Right);
	}
	
	protected virtual void Update() {
		if (!this.registered) {
			this.RegisterWithGlobal();
		}
	}
	
	/**
	 * This will be the main one to override for the children
	 * e.g. quest npcs will pop up the quest window, etc.
	 */
	protected virtual void ClickAction() {
		/**
		 * TODO: do some kind of child notify so that we can cache whether this component exists
		 * The reason is that GetComponent is supposedly not good performance
		 */
		if (!this.gameObject.GetComponent ("BasicWindowGui")) {
			this.gameObject.AddComponent ("BasicWindowGui");
		}
	}
	
	public void Clicked(float distance) {		
		if (distance > DialogueNPC.MAX_TALK_DISTANCE) {
			return;
		}
		
		this.ClickAction ();
	}
	
	public Transform GetTransform() {
		return this.transform;
	}
}
